{% extends "后台管理/template.html" %}

{% block title %}
    联系我们
{% endblock %}

{% block css %}
<style>
    .contact-card {
        background: #fff;
        border-radius: 12px;
        padding: 30px;
        box-shadow: 0 2px 12px rgba(0,0,0,0.08);
    }
    
    .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 30px;
    }
    
    .card-title {
        font-size: 24px;
        font-weight: 600;
        color: #333;
    }
    
    .contact-table {
        margin-top: 20px;
    }
    
    .qr-preview {
        max-width: 100px;
        max-height: 100px;
        cursor: pointer;
    }
    
    .qr-modal .modal-body {
        text-align: center;
    }
    
    .qr-modal img {
        max-width: 300px;
        max-height: 300px;
    }
    
    .form-label {
        font-weight: 500;
    }
    
    .required::after {
        content: '*';
        color: #ff4d4f;
        margin-left: 4px;
    }
    
    /* 加载遮罩样式 */
    #loadingOverlay {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(255, 255, 255, 0.8);
        display: none;
        justify-content: center;
        align-items: center;
        z-index: 9999;
    }

    .spinner-border {
        width: 3rem;
        height: 3rem;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 加载遮罩 -->
    <div id="loadingOverlay">
        <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">加载中...</span>
        </div>
    </div>

    <div class="contact-card">
        <div class="card-header">
            <h1 class="card-title">联系方式管理</h1>
            <button class="btn btn-primary" onclick="showAddModal()">
                <i class='bx bx-plus me-1'></i>添加联系方式
            </button>
        </div>
        
        <!-- 联系方式列表 -->
        <div class="table-responsive contact-table">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>联系方式</th>
                        <th>描述内容</th>
                        <th>二维码</th>
                        <th>创建时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="contactList">
                    <!-- 数据将通过JS动态插入 -->
                </tbody>
            </table>
        </div>
    </div>
    
    <!-- 添加联系方式模态框 -->
    <div class="modal fade" id="addContactModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">添加联系方式</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="contactForm" onsubmit="return false;">
                        <div class="mb-3">
                            <label class="form-label required">联系方式</label>
                            <input type="text" class="form-control" id="contactWay" required>
                            <div class="form-text">例如：QQ群、微信客服等</div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label required">描述内容</label>
                            <textarea class="form-control" id="contactContent" rows="3" required></textarea>
                            <div class="form-text">简要描述该联系方式的用途</div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label required">二维码</label>
                            <input type="file" class="form-control" id="contactQR" accept="image/*" required>
                            <div class="form-text">支持jpg、png格式的图片</div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="submitContact()">确定添加</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 查看二维码模态框 -->
    <div class="modal fade qr-modal" id="viewQRModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">查看二维码</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <img id="qrPreview" src="" alt="二维码">
                </div>
            </div>
        </div>
    </div>

    <!-- 删除确认弹窗 -->
    <div class="modal fade" id="deleteConfirmModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">删除确认</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <p>确定要删除这个联系方式吗？此操作不可恢复。</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-danger" onclick="confirmDelete()">确定删除</button>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block js %}
<script>
let addContactModal = null;
let viewQRModal = null;
let deleteConfirmModal = null;
let deleteContactId = null;  // 存储要删除的联系方式ID

// 显示加载状态
function showLoading() {
    document.getElementById('loadingOverlay').style.display = 'flex';
}

// 隐藏加载状态
function hideLoading() {
    document.getElementById('loadingOverlay').style.display = 'none';
}

// 初始化模态框
document.addEventListener('DOMContentLoaded', function() {
    addContactModal = new bootstrap.Modal(document.getElementById('addContactModal'));
    viewQRModal = new bootstrap.Modal(document.getElementById('viewQRModal'));
    deleteConfirmModal = new bootstrap.Modal(document.getElementById('deleteConfirmModal'));
    getContactList();
});

// 显示添加模态框
function showAddModal() {
    document.getElementById('contactForm').reset();
    addContactModal.show();
}

// 获取联系方式列表
async function getContactList() {
    try {
        showLoading();
        const response = await fetch('/api/system/get_contact_us/');
        const data = await response.json();
        
        if(data.code === 200) {
            renderContactList(data.data);
        } else {
            throw new Error(data.message);
        }
    } catch(error) {
        console.error('获取联系方式失败:', error);
        window.showToast('获取失败: ' + error.message, 'error');
    } finally {
        hideLoading();
    }
}

// 渲染联系方式列表
function renderContactList(contacts) {
    const container = document.getElementById('contactList');
    
    if(!contacts || contacts.length === 0) {
        container.innerHTML = `
            <tr>
                <td colspan="6" class="text-center py-4">暂无联系方式</td>
            </tr>
        `;
        return;
    }
    
    container.innerHTML = contacts.map(contact => `
        <tr>
            <td>${contact.id}</td>
            <td>${contact.contact_way}</td>
            <td>${contact.contact_content}</td>
            <td>
                <img 
                    src="${contact.contact_qr}" 
                    class="qr-preview" 
                    onclick="viewQR('${contact.contact_qr}')"
                    alt="二维码"
                >
            </td>
            <td>${formatDateTime(contact.create_time)}</td>
            <td>
                <button 
                    class="btn btn-danger btn-sm"
                    onclick="deleteContact(${contact.id})"
                >
                    删除
                </button>
            </td>
        </tr>
    `).join('');
}

// 提交添加联系方式
async function submitContact() {
    const form = document.getElementById('contactForm');
    if(!form.checkValidity()) {
        form.reportValidity();
        return;
    }
    
    const formData = new FormData();
    formData.append('contact_way', document.getElementById('contactWay').value);
    formData.append('contact_content', document.getElementById('contactContent').value);
    formData.append('contact_qr', document.getElementById('contactQR').files[0]);
    
    try {
        showLoading();
        const response = await fetch('/api/system/create_contact_us/', {
            method: 'POST',
            body: formData
        });
        
        const data = await response.json();
        if(data.code === 200) {
            // 重置表单并关闭模态框
            document.getElementById('contactForm').reset();
            addContactModal.hide();
            // 刷新数据并显示提示
            await getContactList();
            window.showToast('添加成功', 'success');
        } else {
            throw new Error(data.message);
        }
    } catch(error) {
        console.error('添加失败:', error);
        window.showToast('添加失败: ' + error.message, 'error');
    } finally {
        hideLoading();
    }
}

// 查看二维码
function viewQR(url) {
    document.getElementById('qrPreview').src = url;
    viewQRModal.show();
}

// 格式化日期时间
function formatDateTime(dateStr) {
    const date = new Date(dateStr.replace(/-/g, '/'));
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
}

// 显示删除确认弹窗
function deleteContact(id) {
    deleteContactId = id;  // 保存要删除的ID
    deleteConfirmModal.show();
}

// 确认删除
async function confirmDelete() {
    try {
        showLoading();
        const response = await fetch(`/api/system/delete_contact_us/?contact_us_id=${deleteContactId}`);
        const data = await response.json();
        
        if(data.code === 200) {
            deleteConfirmModal.hide();
            // 刷新数据并显示提示
            await getContactList();
            window.showToast('删除成功', 'success');
        } else {
            throw new Error(data.message);
        }
    } catch(error) {
        console.error('删除失败:', error);
        window.showToast('删除失败: ' + error.message, 'error');
    } finally {
        hideLoading();
        deleteContactId = null;  // 重置ID
    }
}
</script>
{% endblock %}

{% block nav_left %}
{% include '后台管理/components/左侧导航栏.html' %}
{% endblock %}

{% block NavBar %}
{% endblock %}

{% block footer %}{% endblock %}